﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WR.BL.BE;
using SAP.Middleware.Connector;

namespace WR.DL.DALC.SAP
{
    public class SalesOrderDALC
    {
        private string _connId = string.Empty;

        #region Singleton
        public static SalesOrderDALC getInstance(string pConnId)
        {
            if (_instance == null)
            {
                lock (typeof(SalesOrderDALC))
                {
                    if (_instance == null)
                    {
                        _instance = new SalesOrderDALC(pConnId);
                    }
                }
            }
            return _instance;
        }
        private SalesOrderDALC(string pConnId) { this._connId = pConnId; }
        private static volatile SalesOrderDALC _instance = null;
        #endregion

        public List<SalesOrderBE> find(string pTienda, string pClaseDoc, string pNdoc, string pFechaI, string pFecheF)
        {
            SalesOrderBE objSO = null; List<SalesOrderBE> lstSO = new List<SalesOrderBE>();
            IRfcFunction function = null;
            InMemoryDestinationConfiguration dc = new InMemoryDestinationConfiguration();
            try
            {
                //RfcConfigParameters cp = new RfcConfigParameters(); //GenericDALC.getConfigParam(pObjConn);
                //cp.Add(RfcConfigParameters.Name, this._connId);
                //RfcDestination dest = RfcDestinationManager.GetDestination(cp);
                //List<RfcConnectionData> cd = dest.Monitor.GetConnectionsData();
                try
                {
                    RfcDestinationManager.RegisterDestinationConfiguration(dc);
                }
                catch { }
                RfcDestination dest = RfcDestinationManager.GetDestination(this._connId);
                function = dest.Repository.CreateFunction("ZWR_SD_006");

                function.SetValue("I_WERKS", pTienda);
                function.SetValue("I_AUART", pClaseDoc);
                function.SetValue("I_VBELN", pNdoc);
                if (!string.IsNullOrEmpty(pFechaI))
                {
                    DateTime dt1 = Convert.ToDateTime(pFechaI);
                    function.SetValue("I_AUDATI", dt1);
                }
                if (!string.IsNullOrEmpty(pFecheF))
                {
                    DateTime dt2 = Convert.ToDateTime(pFecheF);
                    function.SetValue("I_AUDATF", dt2);
                }
                function.Invoke(dest);

                IRfcTable T_DOCS = function.GetTable("T_DOCS");
                foreach (IRfcStructure s_docs in T_DOCS)
                {
                    objSO = new SalesOrderBE();
                    objSO.Cliente.Codigo = s_docs["KUNNR"].GetString();
                    objSO.Cliente.Descripcion = s_docs["NAME1"].GetString();
                    objSO.NumDoc = s_docs["VBELN"].GetString();
                    objSO.Usuario.Usuario = s_docs["ERNAM"].GetString();

                    objSO.FechaDoc = s_docs["AUDAT"].GetString();
                    objSO.ClaseDoc = s_docs["AUART"].GetString();
                    objSO.ClaseDocT = s_docs["CLDOC"].GetString();
                    objSO.Moneda = s_docs["MONED"].GetString();
                    objSO.CondPago = s_docs["CPAGO"].GetString();
                    objSO.Total = s_docs["NETWR"].GetDecimal();

                    lstSO.Add(objSO);
                }

            }
            catch (RfcCommunicationException e)
            {
                // network problem...
            }
            catch (RfcLogonException e)
            {
                // user could not logon...
            }
            catch (RfcAbapRuntimeException e)
            {
                // serious problem on ABAP system side...
            }
            catch (RfcAbapBaseException e)
            {
                // The function module returned an ABAP exception, an ABAP message
                // or an ABAP class-based exception...
            }
            catch (RfcBaseException e)
            {
                // Grabar Log de errores con e.message
                throw new Exception(e.Message);
            }
            finally
            {
                RfcDestinationManager.UnregisterDestinationConfiguration(dc);
            }
            return lstSO;
        }

        public string save(SalesOrderBE pSO, out string oNumDoc, string valida)
        {
            oNumDoc = string.Empty;
            string strTipo = string.Empty; string retVal = string.Empty;
            //SalesOrderBE objSO = null;
            List<SalesOrderBE> lstSO = new List<SalesOrderBE>();
            IRfcFunction function = null;
            InMemoryDestinationConfiguration dc = new InMemoryDestinationConfiguration();
            try
            {
                //RfcConfigParameters cp = new RfcConfigParameters(); //GenericDALC.getConfigParam(pObjConn);
                //cp.Add(RfcConfigParameters.Name, this._connId);
                //RfcDestination dest = RfcDestinationManager.GetDestination(cp);
                //List<RfcConnectionData> cd = dest.Monitor.GetConnectionsData();
                try
                {
                    RfcDestinationManager.RegisterDestinationConfiguration(dc);
                }
                catch { }
                
                RfcDestination dest = RfcDestinationManager.GetDestination(this._connId);
                function = dest.Repository.CreateFunction("ZWR_SD_003");

                IRfcStructure I_HEADER = function.GetStructure("I_HEADER");
                IRfcTable T_ITEMS = function.GetTable("T_ITEMS");
                IRfcTable T_PARTNERS = function.GetTable("T_PARTNERS");
                IRfcTable T_COND = function.GetTable("T_COND");

                I_HEADER.SetValue("DOC_TYPE", pSO.ClaseDoc);//Clase de documento
                I_HEADER.SetValue("SALES_ORG", "1000");//Organización de ventas
                I_HEADER.SetValue("DISTR_CHAN", "01");//Canal de distribución
                I_HEADER.SetValue("DIVISION", "01");//Sector
                I_HEADER.SetValue("SALES_OFF", pSO.Usuario.Tienda);//Oficina de ventas
                I_HEADER.SetValue("PMNTTRMS", pSO.Cliente.CondPago);//Clave de condiciones de pago
                I_HEADER.SetValue("SHIP_COND", pSO.Cliente.Lprio);//Condición de expedición

                int i = 0; 
                T_ITEMS.Insert(pSO.Detalle.Count);
                T_COND.Insert(pSO.Detalle.Count);
                foreach (DetailBE objDet in pSO.Detalle)
                {
                    T_ITEMS[i].SetValue("ITM_NUMBER", objDet.Pos);
                    T_ITEMS[i].SetValue("MATERIAL", objDet.Material.Codigo);
                    T_ITEMS[i].SetValue("PLANT", pSO.Usuario.Tienda);
                    //T_ITEMS[i].SetValue("STORE_LOC", "0001");
                    T_ITEMS[i].SetValue("TARGET_QTY", objDet.Cant);
                    i++;
                }

                // Interlocutores
                
                T_PARTNERS.Insert(4);
                T_PARTNERS[0].SetValue("PARTN_ROLE", "AG");
                T_PARTNERS[0].SetValue("PARTN_NUMB", pSO.Cliente.Codigo);
                T_PARTNERS[1].SetValue("PARTN_ROLE", "RE");
                T_PARTNERS[1].SetValue("PARTN_NUMB", pSO.Cliente.Codigo);
                T_PARTNERS[2].SetValue("PARTN_ROLE", "RG");
                T_PARTNERS[2].SetValue("PARTN_NUMB", pSO.Cliente.Codigo);
                T_PARTNERS[3].SetValue("PARTN_ROLE", "WE");
                T_PARTNERS[3].SetValue("PARTN_NUMB", pSO.Cliente.Codigo);
                if (valida == "1")
                {
                    T_PARTNERS[0].SetValue("NAME", pSO.Cliente.nomCli);
                    T_PARTNERS[0].SetValue("STREET", pSO.Cliente.direCli);
                    T_PARTNERS[0].SetValue("POSTL_CODE", pSO.Cliente.poscodCli);
                    T_PARTNERS[0].SetValue("CITY", pSO.Cliente.cityCli);
                    T_PARTNERS[0].SetValue("REGION", pSO.Cliente.regionCli);
                    T_PARTNERS[0].SetValue("TELEPHONE", pSO.Cliente.telefCli);
                    T_PARTNERS[0].SetValue("TELETEX_NO", pSO.Cliente.correoCli);
                    T_PARTNERS[0].SetValue("TELEBOX", pSO.Cliente.rucdniCli);
                    T_PARTNERS[0].SetValue("COUNTRY", "PE");
                    T_PARTNERS[0].SetValue("LANGU", "S");

                    T_PARTNERS[1].SetValue("NAME", pSO.Cliente.nomCli);
                    T_PARTNERS[1].SetValue("STREET", pSO.Cliente.direCli);
                    T_PARTNERS[1].SetValue("POSTL_CODE", pSO.Cliente.poscodCli);
                    T_PARTNERS[1].SetValue("CITY", pSO.Cliente.cityCli);
                    T_PARTNERS[1].SetValue("REGION", pSO.Cliente.regionCli);
                    T_PARTNERS[1].SetValue("TELEPHONE", pSO.Cliente.telefCli);
                    T_PARTNERS[1].SetValue("TELETEX_NO", pSO.Cliente.correoCli);
                    T_PARTNERS[1].SetValue("TELEBOX", pSO.Cliente.rucdniCli);
                    T_PARTNERS[1].SetValue("COUNTRY", "PE");
                    T_PARTNERS[1].SetValue("LANGU", "S");

                    T_PARTNERS[2].SetValue("NAME", pSO.Cliente.nomCli);
                    T_PARTNERS[2].SetValue("STREET", pSO.Cliente.direCli);
                    T_PARTNERS[2].SetValue("POSTL_CODE", pSO.Cliente.poscodCli);
                    T_PARTNERS[2].SetValue("CITY", pSO.Cliente.cityCli);
                    T_PARTNERS[2].SetValue("REGION", pSO.Cliente.regionCli);
                    T_PARTNERS[2].SetValue("TELEPHONE", pSO.Cliente.telefCli);
                    T_PARTNERS[2].SetValue("TELETEX_NO", pSO.Cliente.correoCli);
                    T_PARTNERS[2].SetValue("TELEBOX", pSO.Cliente.rucdniCli);
                    T_PARTNERS[2].SetValue("COUNTRY", "PE");
                    T_PARTNERS[2].SetValue("LANGU", "S");

                    T_PARTNERS[3].SetValue("NAME", pSO.Cliente.nomCli);
                    T_PARTNERS[3].SetValue("STREET", pSO.Cliente.direCli);
                    T_PARTNERS[3].SetValue("POSTL_CODE", pSO.Cliente.poscodCli);
                    T_PARTNERS[3].SetValue("CITY", pSO.Cliente.cityCli);
                    T_PARTNERS[3].SetValue("REGION", pSO.Cliente.regionCli);
                    T_PARTNERS[3].SetValue("TELEPHONE", pSO.Cliente.telefCli);
                    T_PARTNERS[3].SetValue("TELETEX_NO", pSO.Cliente.correoCli);
                    T_PARTNERS[3].SetValue("TELEBOX", pSO.Cliente.rucdniCli);
                    T_PARTNERS[3].SetValue("COUNTRY", "PE");
                    T_PARTNERS[3].SetValue("LANGU", "S");
                }
                
                function.Invoke(dest);

                oNumDoc = function.GetString("E_VBELN");
                IRfcTable T_RETURN = function.GetTable("T_RETURN");

                if (string.IsNullOrEmpty(oNumDoc))
                {
                    foreach (IRfcStructure S_RETURN in T_RETURN)
                    {
                        strTipo = S_RETURN["TYPE"].GetString();
                        if (strTipo.Equals("A") || strTipo.Equals("E"))
                        {
                            retVal += S_RETURN["MESSAGE"].GetString() + "\r\n";
                        }
                    }
                }
                else
                {
                    //RGF 20111102
                    //retVal = T_RETURN[T_RETURN.Count - 1].GetString("MESSAGE");
                    retVal = T_RETURN[T_RETURN.Count - 2].GetString("MESSAGE") + "\r\n" +
                                T_RETURN[T_RETURN.Count - 1].GetString("MESSAGE");
                }
            }
            catch (RfcCommunicationException e)
            {
                // network problem...
                retVal = e.Message;
            }
            catch (RfcLogonException e)
            {
                // user could not logon...
                retVal = e.Message;
            }
            catch (RfcAbapRuntimeException e)
            {
                // serious problem on ABAP system side...
                retVal = e.Message;
            }
            catch (RfcAbapBaseException e)
            {
                // The function module returned an ABAP exception, an ABAP message
                // or an ABAP class-based exception...
                retVal = e.Message;
            }
            catch (RfcBaseException e)
            {
                // Grabar Log de errores con e.message
                retVal = e.Message;
            }
            finally
            {
                RfcDestinationManager.UnregisterDestinationConfiguration(dc);
                retVal = retVal.Replace("\r\n", "<br />");//RGF 20111102
            }
            return retVal;
        }

        public string sendCorreo(string pCorreo, string pNroDoc, string pTipDoc, string pClasDoc)
        {
            string retVal = string.Empty;
            SalesOrderBE objSO = new SalesOrderBE();
            IRfcFunction function = null;
            InMemoryDestinationConfiguration dc = new InMemoryDestinationConfiguration();
            try
            {
                try
                {
                    RfcDestinationManager.RegisterDestinationConfiguration(dc);
                }
                catch { }
                RfcDestination dest = RfcDestinationManager.GetDestination(this._connId);
                function = dest.Repository.CreateFunction("ZWR_SD_016");
                function.SetValue("I_CORREO", pCorreo);
                function.SetValue("I_NRODOC", pNroDoc);
                function.SetValue("I_TIPODOC", pTipDoc);
                function.SetValue("I_CLASDOC", pClasDoc);

                function.Invoke(dest);
                retVal = function.GetString("E_RETURN");
            }
            catch (RfcCommunicationException e)
            {
                // network problem...
                retVal = e.Message;
            }
            catch (RfcLogonException e)
            {
                // user could not logon...
                retVal = e.Message;
            }
            catch (RfcAbapRuntimeException e)
            {
                // serious problem on ABAP system side...
                retVal = e.Message;
            }
            catch (RfcAbapBaseException e)
            {
                // The function module returned an ABAP exception, an ABAP message
                // or an ABAP class-based exception...
                retVal = e.Message;
            }
            catch (RfcBaseException e)
            {
                // Grabar Log de errores con e.message
                retVal = e.Message;
            }
            finally
            {
                RfcDestinationManager.UnregisterDestinationConfiguration(dc);
            }
            return retVal;
        }

        public string read(string strCotId, out SalesOrderBE oSalesOrder)
        {
            //string strTipo = string.Empty; 
            string retVal = string.Empty;
            SalesOrderBE objSO = new SalesOrderBE();
            oSalesOrder = new SalesOrderBE();

            IRfcFunction function = null;
            InMemoryDestinationConfiguration dc = new InMemoryDestinationConfiguration();
            try
            {
                //RfcConfigParameters cp = new RfcConfigParameters(); //GenericDALC.getConfigParam(pObjConn);
                //cp.Add(RfcConfigParameters.Name, this._connId);
                //RfcDestination dest = RfcDestinationManager.GetDestination(cp);
                //List<RfcConnectionData> cd = dest.Monitor.GetConnectionsData();
                try
                {
                    RfcDestinationManager.RegisterDestinationConfiguration(dc);
                }
                catch { }
                RfcDestination dest = RfcDestinationManager.GetDestination(this._connId);

                function = dest.Repository.CreateFunction("ZWR_SD_004");
                function.SetValue("I_VBELN", strCotId);

                function.Invoke(dest);

                IRfcStructure E_VBAK = function.GetStructure("E_VBAK");
                IRfcStructure E_VBPA = function.GetStructure("E_VBPA");
                IRfcTable T_VBAP = function.GetTable("T_VBAP");

                if (E_VBAK.Count == 0)
                {
                    oSalesOrder = null;
                    throw new Exception("No se encontró el documento solicitado.");
                }

                //objSO.Cliente = ClientDALC.getInstance(this._connId).read(E_VBAK.GetString("KUNNR"));
                objSO.Cliente.Codigo = E_VBAK.GetString("KUNNR");//solicitante
                objSO.Cliente.Descripcion = E_VBAK.GetString("NAME1");//solicitante
                objSO.Cliente.Ruc = E_VBAK.GetString("STCD1");
                objSO.Total = E_VBAK.GetDecimal("NETWR");//valor neto
                objSO.Usuario.Usuario = E_VBAK.GetString("ERNAM");
                //objSO.Usuario.Tienda = E_VBAK.GetString("VKBUR");
                objSO.NumDoc = E_VBAK.GetString("VBELN");
                objSO.ClaseDoc = E_VBAK.GetString("AUART");
                objSO.ClaseDocT = E_VBAK.GetString("CLDOC");
                objSO.Moneda = E_VBAK.GetString("MONED");
                objSO.CondPago = E_VBAK.GetString("CPAGO");
                objSO.FechaDoc = E_VBAK.GetString("AUDAT");
                objSO.Cliente.nomCli = E_VBPA.GetString("NAME1");
                objSO.Cliente.direCli = E_VBPA.GetString("STREET");
                objSO.Cliente.cityCli = E_VBPA.GetString("CITY1");
                objSO.Cliente.correoCli = E_VBPA.GetString("SMTP_ADDR");
                objSO.Cliente.poscodCli = E_VBPA.GetString("POST_CODE1");
                objSO.Cliente.regionCli = E_VBPA.GetString("REGION");
                objSO.Cliente.telefCli = E_VBPA.GetString("TEL_NUMBER");
                objSO.Cliente.rucdniCli = E_VBPA.GetString("STCD1");


                DetailBE objDet = null;
                foreach (IRfcStructure S_VBAP in T_VBAP)
                {
                    objDet = new DetailBE();
                    objDet.Pos = S_VBAP.GetInt("POSNR").ToString();
                    objDet.Material.Codigo = S_VBAP.GetString("MATNR");
                    objDet.Material.Descripcion = S_VBAP.GetString("ARKTX");
                    objDet.Material.Ean = S_VBAP.GetString("EAN11");
                    objDet.Cant = S_VBAP.GetDecimal("KWMENG");
                    objDet.UMedida = S_VBAP.GetString("VRKME");
                    objDet.PesoBruto = S_VBAP.GetDecimal("BRGEW");//peso bruto
                    objDet.PesoNeto = S_VBAP.GetDecimal("NTGEW");//peso neto
                    objDet.Material.Precio = S_VBAP.GetDecimal("KBETR");//precio unitario
                    //objDet.Total = S_VBAP.GetDecimal("KWERT");//precio total
                    objDet.ImporteTotal = S_VBAP.GetDecimal("KWERT");//RGF 20111102
                    objDet.DescuentoTotal = S_VBAP.GetDecimal("DCTOTOT");//RGF 20111027

                    objSO.Detalle.Add(objDet);
                }

                oSalesOrder = objSO;
            }
            catch (RfcCommunicationException e)
            {
                // network problem...
                retVal = e.Message;
            }
            catch (RfcLogonException e)
            {
                // user could not logon...
                retVal = e.Message;
            }
            catch (RfcAbapRuntimeException e)
            {
                // serious problem on ABAP system side...
                retVal = e.Message;
            }
            catch (RfcAbapBaseException e)
            {
                // The function module returned an ABAP exception, an ABAP message
                // or an ABAP class-based exception...
                retVal = e.Message;
            }
            catch (RfcBaseException e)
            {
                // Grabar Log de errores con e.message
                retVal = e.Message;
            }
            finally
            {
                RfcDestinationManager.UnregisterDestinationConfiguration(dc);
            }
            return retVal;
        }

        public string update(SalesOrderBE pSO, out bool oModificado, string valida)
        {
            oModificado = false;
            string strTipo = string.Empty; string retVal = string.Empty;
            List<SalesOrderBE> lstSO = new List<SalesOrderBE>();
            IRfcFunction function = null;
            InMemoryDestinationConfiguration dc = new InMemoryDestinationConfiguration();
            try
            {
                //RfcConfigParameters cp = new RfcConfigParameters(); //GenericDALC.getConfigParam(pObjConn);
                //cp.Add(RfcConfigParameters.Name, this._connId);
                //RfcDestination dest = RfcDestinationManager.GetDestination(cp);
                //List<RfcConnectionData> cd = dest.Monitor.GetConnectionsData();
                try
                {
                    RfcDestinationManager.RegisterDestinationConfiguration(dc);
                }
                catch { }
                RfcDestination dest = RfcDestinationManager.GetDestination(this._connId);
                function = dest.Repository.CreateFunction("ZWR_SD_007");
                function.SetValue("I_VBELN", pSO.NumDoc);
                //IRfcStructure I_HEADER = function.GetStructure("I_HEADER");
                IRfcTable T_ITEMS = function.GetTable("T_ITEMS");
                IRfcTable T_PARTNERS = function.GetTable("T_PARTNERS");

                //I_HEADER.SetValue("DOC_TYPE", pSO.ClaseDoc);//Clase de documento
                //I_HEADER.SetValue("SALES_ORG", "1000");//Organización de ventas
                //I_HEADER.SetValue("DISTR_CHAN", "01");//Canal de distribución
                //I_HEADER.SetValue("DIVISION", "01");//Sector
                //I_HEADER.SetValue("SALES_OFF", pSO.Usuario.Tienda);//Oficina de ventas
                //I_HEADER.SetValue("PMNTTRMS", pSO.Cliente.CondPago);//Clave de condiciones de pago
                //I_HEADER.SetValue("SHIP_COND", pSO.Cliente.Lprio);//Condición de expedición

                int i = 0;
                T_ITEMS.Insert(pSO.Detalle.Count);
                foreach (DetailBE objDet in pSO.Detalle)
                {
                    T_ITEMS[i].SetValue("ITM_NUMBER", objDet.Pos);
                    T_ITEMS[i].SetValue("MATERIAL", objDet.Material.Codigo);
                    T_ITEMS[i].SetValue("PLANT", pSO.Usuario.Tienda);
                    //T_ITEMS[i].SetValue("STORE_LOC", "0001");
                    T_ITEMS[i].SetValue("TARGET_QTY", objDet.Cant);
                    i++;
                }

                // Interlocutores
                T_PARTNERS.Insert(4);
                T_PARTNERS[0].SetValue("PARTN_ROLE", "AG");
                T_PARTNERS[0].SetValue("PARTN_NUMB", pSO.Cliente.Codigo);
                T_PARTNERS[1].SetValue("PARTN_ROLE", "RE");
                T_PARTNERS[1].SetValue("PARTN_NUMB", pSO.Cliente.Codigo);
                T_PARTNERS[2].SetValue("PARTN_ROLE", "RG");
                T_PARTNERS[2].SetValue("PARTN_NUMB", pSO.Cliente.Codigo);
                T_PARTNERS[3].SetValue("PARTN_ROLE", "WE");
                T_PARTNERS[3].SetValue("PARTN_NUMB", pSO.Cliente.Codigo);
                if (valida == "1")
                {
                    T_PARTNERS[0].SetValue("NAME", pSO.Cliente.nomCli);
                    T_PARTNERS[0].SetValue("STREET", pSO.Cliente.direCli);
                    T_PARTNERS[0].SetValue("POSTL_CODE", pSO.Cliente.poscodCli);
                    T_PARTNERS[0].SetValue("CITY", pSO.Cliente.cityCli);
                    T_PARTNERS[0].SetValue("REGION", pSO.Cliente.regionCli);
                    T_PARTNERS[0].SetValue("TELEPHONE", pSO.Cliente.telefCli);
                    T_PARTNERS[0].SetValue("TELETEX_NO", pSO.Cliente.correoCli);
                    T_PARTNERS[0].SetValue("TELEBOX", pSO.Cliente.rucdniCli);
                    T_PARTNERS[0].SetValue("COUNTRY", "PE");
                    T_PARTNERS[0].SetValue("LANGU", "S");

                    T_PARTNERS[1].SetValue("NAME", pSO.Cliente.nomCli);
                    T_PARTNERS[1].SetValue("STREET", pSO.Cliente.direCli);
                    T_PARTNERS[1].SetValue("POSTL_CODE", pSO.Cliente.poscodCli);
                    T_PARTNERS[1].SetValue("CITY", pSO.Cliente.cityCli);
                    T_PARTNERS[1].SetValue("REGION", pSO.Cliente.regionCli);
                    T_PARTNERS[1].SetValue("TELEPHONE", pSO.Cliente.telefCli);
                    T_PARTNERS[1].SetValue("TELETEX_NO", pSO.Cliente.correoCli);
                    T_PARTNERS[1].SetValue("TELEBOX", pSO.Cliente.rucdniCli);
                    T_PARTNERS[1].SetValue("COUNTRY", "PE");
                    T_PARTNERS[1].SetValue("LANGU", "S");

                    T_PARTNERS[2].SetValue("NAME", pSO.Cliente.nomCli);
                    T_PARTNERS[2].SetValue("STREET", pSO.Cliente.direCli);
                    T_PARTNERS[2].SetValue("POSTL_CODE", pSO.Cliente.poscodCli);
                    T_PARTNERS[2].SetValue("CITY", pSO.Cliente.cityCli);
                    T_PARTNERS[2].SetValue("REGION", pSO.Cliente.regionCli);
                    T_PARTNERS[2].SetValue("TELEPHONE", pSO.Cliente.telefCli);
                    T_PARTNERS[2].SetValue("TELETEX_NO", pSO.Cliente.correoCli);
                    T_PARTNERS[2].SetValue("TELEBOX", pSO.Cliente.rucdniCli);
                    T_PARTNERS[2].SetValue("COUNTRY", "PE");
                    T_PARTNERS[2].SetValue("LANGU", "S");

                    T_PARTNERS[3].SetValue("NAME", pSO.Cliente.nomCli);
                    T_PARTNERS[3].SetValue("STREET", pSO.Cliente.direCli);
                    T_PARTNERS[3].SetValue("POSTL_CODE", pSO.Cliente.poscodCli);
                    T_PARTNERS[3].SetValue("CITY", pSO.Cliente.cityCli);
                    T_PARTNERS[3].SetValue("REGION", pSO.Cliente.regionCli);
                    T_PARTNERS[3].SetValue("TELEPHONE", pSO.Cliente.telefCli);
                    T_PARTNERS[3].SetValue("TELETEX_NO", pSO.Cliente.correoCli);
                    T_PARTNERS[3].SetValue("TELEBOX", pSO.Cliente.rucdniCli);
                    T_PARTNERS[3].SetValue("COUNTRY", "PE");
                    T_PARTNERS[3].SetValue("LANGU", "S");
                }

                function.Invoke(dest);

                string errCatch = function.GetString("E_RESULT");
                IRfcTable T_RETURN = function.GetTable("T_RETURN");

                if (string.IsNullOrEmpty(errCatch))
                {
                    foreach (IRfcStructure S_RETURN in T_RETURN)
                    {
                        strTipo = S_RETURN["TYPE"].GetString();
                        if (strTipo.Equals("A") || strTipo.Equals("E")) //A:Abort E:Error
                        {
                            retVal += S_RETURN["MESSAGE"].GetString() + "\r\n";
                        }
                    }
                    if (string.IsNullOrEmpty(retVal))
                    {
                        //RGF 20111102
                        retVal = T_RETURN[T_RETURN.Count - 2].GetString("MESSAGE") + "\r\n" +
                                T_RETURN[T_RETURN.Count - 1].GetString("MESSAGE");
                        oModificado = true;
                    }
                }
                else
                {
                    retVal = "Error ABAP: " + errCatch;
                }
            }
            catch (RfcCommunicationException e)
            {
                // network problem...
                retVal = e.Message;
            }
            catch (RfcLogonException e)
            {
                // user could not logon...
                retVal = e.Message;
            }
            catch (RfcAbapRuntimeException e)
            {
                // serious problem on ABAP system side...
                retVal = e.Message;
            }
            catch (RfcAbapBaseException e)
            {
                // The function module returned an ABAP exception, an ABAP message
                // or an ABAP class-based exception...
                retVal = e.Message;
            }
            catch (RfcBaseException e)
            {
                // Grabar Log de errores con e.message
                retVal = e.Message;
            }
            finally
            {
                RfcDestinationManager.UnregisterDestinationConfiguration(dc);
                retVal = retVal.Replace("\r\n", "<br />");//RGF 20111102
            }
            return retVal;
        }

        public List<GenericBE> getRegiones()
        {
            GenericBE objRE = null; List<GenericBE> lstRE = new List<GenericBE>();
            IRfcFunction function = null;
            InMemoryDestinationConfiguration dc = new InMemoryDestinationConfiguration();
            try
            {
                //RfcConfigParameters cp = new RfcConfigParameters(); //GenericDALC.getConfigParam(pObjConn);
                //cp.Add(RfcConfigParameters.Name, this._connId);
                //RfcDestination dest = RfcDestinationManager.GetDestination(cp);
                //List<RfcConnectionData> cd = dest.Monitor.GetConnectionsData();
                try
                {
                    RfcDestinationManager.RegisterDestinationConfiguration(dc);
                }
                catch { }
                RfcDestination dest = RfcDestinationManager.GetDestination(this._connId);

                function = dest.Repository.CreateFunction("ZWR_SD_014");
                function.Invoke(dest);

                IRfcTable T_ZREGIO = function.GetTable("T_ZREGIO");
                foreach (IRfcStructure S_ZREGIO in T_ZREGIO)
                {
                    objRE = new GenericBE();
                    objRE.codregion = S_ZREGIO["REGIO"].GetString();
                    objRE.nomRegion = S_ZREGIO["BEZEI20"].GetString();

                    lstRE.Add(objRE);
                }

            }
            catch (RfcCommunicationException e)
            {
                // network problem...
            }
            catch (RfcLogonException e)
            {
                // user could not logon...
            }
            catch (RfcAbapRuntimeException e)
            {
                // serious problem on ABAP system side...
            }
            catch (RfcAbapBaseException e)
            {
                // The function module returned an ABAP exception, an ABAP message
                // or an ABAP class-based exception...
            }
            catch (RfcBaseException e)
            {
                // Grabar Log de errores con e.message
                throw new Exception(e.Message);
            }
            finally
            {
                RfcDestinationManager.UnregisterDestinationConfiguration(dc);
            }
            return lstRE;
        }

        public List<GenericBE> getClaseDoc(string pCod, string pDesc)
        {
            GenericBE objCD = null; List<GenericBE> lstCD = new List<GenericBE>();
            IRfcFunction function = null;
            InMemoryDestinationConfiguration dc = new InMemoryDestinationConfiguration();
            try
            {
                //RfcConfigParameters cp = new RfcConfigParameters(); //GenericDALC.getConfigParam(pObjConn);
                //cp.Add(RfcConfigParameters.Name, this._connId);
                //RfcDestination dest = RfcDestinationManager.GetDestination(cp);
                //List<RfcConnectionData> cd = dest.Monitor.GetConnectionsData();
                try
                {
                    RfcDestinationManager.RegisterDestinationConfiguration(dc);
                }
                catch { }
                RfcDestination dest = RfcDestinationManager.GetDestination(this._connId);

                function = dest.Repository.CreateFunction("ZWR_SD_005");
                function.SetValue("I_AUART", pCod);
                function.SetValue("I_BEZEI", pDesc);

                function.Invoke(dest);

                IRfcTable T_TVAKT = function.GetTable("T_TVAKT");
                foreach (IRfcStructure S_TVAKT in T_TVAKT)
                {
                    objCD = new GenericBE();
                    objCD.Codigo = S_TVAKT["AUART"].GetString();
                    objCD.Descripcion = S_TVAKT["BEZEI"].GetString();

                    lstCD.Add(objCD);
                }

            }
            catch (RfcCommunicationException e)
            {
                // network problem...
            }
            catch (RfcLogonException e)
            {
                // user could not logon...
            }
            catch (RfcAbapRuntimeException e)
            {
                // serious problem on ABAP system side...
            }
            catch (RfcAbapBaseException e)
            {
                // The function module returned an ABAP exception, an ABAP message
                // or an ABAP class-based exception...
            }
            catch (RfcBaseException e)
            {
                // Grabar Log de errores con e.message
                throw new Exception(e.Message);
            }
            finally
            {
                RfcDestinationManager.UnregisterDestinationConfiguration(dc);
            }
            return lstCD;
        }

        public DocImprBE find(string pNdoc)
        {
            DocImprBE    rpta = new DocImprBE();

            CabeceraImprBE cabecera = new CabeceraImprBE(); 
            List<DetalleBE> lstobj = new List<DetalleBE>();
            IRfcFunction function = null;
            InMemoryDestinationConfiguration dc = new InMemoryDestinationConfiguration();
            try
            {
                //RfcConfigParameters cp = new RfcConfigParameters(); //GenericDALC.getConfigParam(pObjConn);
                //cp.Add(RfcConfigParameters.Name, this._connId);
                //RfcDestination dest = RfcDestinationManager.GetDestination(cp);
                //List<RfcConnectionData> cd = dest.Monitor.GetConnectionsData();
                try
                {
                    RfcDestinationManager.RegisterDestinationConfiguration(dc);
                }
                catch { }
                RfcDestination dest = RfcDestinationManager.GetDestination(this._connId);
                function = dest.Repository.CreateFunction("ZWR_SD_008");
                function.SetValue("PI_NRODOC", pNdoc.PadLeft(10,'0'));
                function.Invoke(dest);
                //-----------------------------------------------------
                IRfcTable TCABECERA = function.GetTable("PE_TCABECERA");
                foreach (IRfcStructure s_cabe in TCABECERA)
                {
                    //cabecera.Atencion = s_cabe["ATECION"].GetString();
                    cabecera.Cliente = s_cabe["NAME1"].GetString();
                    cabecera.Fax = s_cabe["TELFX"].GetString();
                    cabecera.Fecha = s_cabe["AUDAT"].GetString();
                    cabecera.FPago = s_cabe["FPAGO"].GetString();
                    cabecera.Hora = s_cabe["HORA"].GetString();
                    cabecera.Moneda = s_cabe["MONED"].GetString();
                    cabecera.NroPedido = s_cabe["VBELN"].GetString();
                    cabecera.RUC = s_cabe["STCD1"].GetString();
                    cabecera.Telf = s_cabe["TELF"].GetString();
                    cabecera.Usuario = s_cabe["ERNAM"].GetString();                
                }
                //-----------------------------------------------------
                IRfcTable TDETALLE = function.GetTable("PE_TDETALLE");
                foreach (IRfcStructure s_detalle in TDETALLE)
                {
                    DetalleBE  objSO = new DetalleBE();
                    objSO.CodMat    = s_detalle["MATNR"].GetString();
                    objSO.Material  = s_detalle["MAKTG"].GetString();
                    objSO.Precio    = s_detalle["ZMENG"].GetDecimal();
                    objSO.Cant      = s_detalle["NETPR"].GetDecimal();
                    objSO.Total     = s_detalle["TOTAL"].GetDecimal();
                    cabecera.Total  = cabecera.Total + objSO.Total;
                    lstobj.Add(objSO);
                }
                rpta.Cabecera = cabecera;
                rpta.Detalle = lstobj;

            }
            catch (RfcCommunicationException e)
            {
                // network problem...
            }
            catch (RfcLogonException e)
            {
                // user could not logon...
            }
            catch (RfcAbapRuntimeException e)
            {
                // serious problem on ABAP system side...
            }
            catch (RfcAbapBaseException e)
            {
                // The function module returned an ABAP exception, an ABAP message
                // or an ABAP class-based exception...
            }
            catch (RfcBaseException e)
            {
                // Grabar Log de errores con e.message
                throw new Exception(e.Message);
            }
            finally
            {
                RfcDestinationManager.UnregisterDestinationConfiguration(dc);
            }
            return rpta;
        }


    }
}
